/*
  GCC Tools 4 ARm requires some handlers when stdio is in use.
  Usually, they are handled by OS, this time we need to own them!
*/

/*
 Needed when stdio in use adn GCC is "GNU TOOLS 4 ARM"
*/
// int _getpid(void){
//    return 0;
// }

// int _kill(int pid){
//    return 0;
// }

// int _exit(void){
//     return 0;
// }

#include <errno.h>
#include <sys/stat.h>
#include <sys/unistd.h>
#include <sys/types.h>
#include "types.h"
#include "errors.h"

#define HEAPSIZE   512
static unsigned char HEAP[HEAPSIZE] __attribute__((section(".heap_buffer")));
/*
 Needed when stdio in use
*/

U32 SBRK_HeapUse;

caddr_t _sbrk ( int incr )
{
  static unsigned char *heap = NULL;
  unsigned char *prev_heap;
  SBRK_HeapUse+=incr;

  if (heap == NULL) {
    heap = (unsigned char *)&HEAP;
    SBRK_HeapUse = 0;
  }
  prev_heap = heap;
  /* check removed to show basic approach */

  heap += incr;

  return (caddr_t) prev_heap;
}


int _write(int file, char *ptr, int len) {
   return len;
}

int _close(int file) {
    return -1;
}

/*
 lseek
 Set position in a file. Minimal implementation:
 */
int _lseek(int file, int ptr, int dir) {
    return 0;
}


/*
 read
 Read a character to a file. `libc' subroutines will use this system routine for input from all files, including stdin
 Returns -1 on error or blocks until the number of characters have been read.
 */
int _read(int file, char *ptr, int len) {
    return len;
}


/*
 fstat
 Status of an open file. For consistency with other minimal implementations in these examples,
 all files are regarded as character special devices.
 The `sys/stat.h' header file required is distributed in the `include' subdirectory for this C library.
 */
int _fstat(int file, struct stat *st) {
    st->st_mode = S_IFCHR;
    return 0;
}


/*
 isatty
 Query whether output stream is a terminal. For consistency with the other minimal implementations,
 */
int _isatty(int file) {
    switch (file){
    case STDOUT_FILENO:
    case STDERR_FILENO:
    case STDIN_FILENO:
        return 1;
    default:
        //errno = ENOTTY;
        errno = EBADF;
        return 0;
    }
}


/** _exit*/
void _exit(int stat)
{
   ASSERT(1);
   while(1){;}
}


/*--------------------------------
 * These two guys became needed after RSA added, probably from DIV3
 * */
/** _kill*/
void _kill(void){
    ASSERT(1);
    while(1){;}
}
/** _getpid*/
void _getpid(void){
    ASSERT(1);
    while(1){;}
}



